//
//  EFModifyPasswordViewController.m
//  J智现场
//
//  Created by song on 2017/12/13.
//  Copyright © 2017年 王长飞. All rights reserved.
//

#import "YejiModel.h"
#import "YejiViewController.h"
#import "EFPickerView.h"

@interface YejiTypeBtn : UIButton

@property(nonatomic,strong) UILabel * titLabel;

@end

@implementation YejiTypeBtn

- (instancetype)initWithFrame:(CGRect)frame{
    
    if ([super initWithFrame:frame]) {
        
        _titLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width,self.frame.size.height)];
        _titLabel.textColor = kTitleColor_midden;
        _titLabel.font = [UIFont systemFontOfSize:14];
        _titLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_titLabel];
        
    }
    
    return self;
}

@end

@interface YejiViewController ()<UIScrollViewDelegate,BaseModelProtocol>
{
    UIImageView *_coverView;
    UIView *_bgView;
    UIDatePicker *_datePicker;
}
@property (nonatomic,strong)YejiModel *yejiModel;

@property (nonatomic,strong)UIScrollView *scrollView;

@property(nonatomic, strong)UIView *topView;
@property(nonatomic, strong)UIView *typeSelectView;
@property(nonatomic, strong)UIView *dateView;
@property(nonatomic, assign)int selectIndex;

@property(nonatomic, strong)UIView *myYejiBgView;
@property(nonatomic, strong)UIView *teamYejiBgView;
@property(nonatomic, strong)UIView *myCommsionBgView;
@property(nonatomic, strong)UILabel *dateLabel;
@property(nonatomic, strong) EFPickerView *pickerView;
@property(nonatomic, strong)NSString *dateString;
@property(nonatomic, strong)NSMutableArray *data;
@property(nonatomic, strong)NSString *minDateStr;


@end

@implementation YejiViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

}

- (void)initView
{
    [super initView];
    [self.navBarView addTitle:@"业绩"];
    
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.topView];
    [self.scrollView addSubview:self.typeSelectView];
    [self.scrollView addSubview:self.dateView];
    [self addViews];
    
    self.selectIndex = 0;
    self.minDateStr = @"2020-02";
    [self.yejiModel getMyYejiDataWith:self.dateLabel.text];
}

- (void)handleModelError:(id)sender error:(NSError *)error{
    
    [self hideHUD];
}

- (void)getDataFinish:(BaseModel *)baseModel netResponse:(BaseResponse *)response{
    
    [self hideHUD];
    
    YejiResponse *resp = (YejiResponse *)response;
    NSDictionary *resObject = resp.resObject;
    if(self.selectIndex == 0){
        [self.myYejiBgView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self setMyYejiWith:resObject];
    }
    else if(self.selectIndex == 1){
        [self.teamYejiBgView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self setTeamYejiWith:resObject];
    }
    else if(self.selectIndex == 2){
        [self.myCommsionBgView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self setMyCommissionDataWith:resObject];
    }
    
}

- (void)dateBgViewTap
{

    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    _coverView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _coverView.image = [UIImage imageNamed:@"data_add_tap"];
    _coverView.userInteractionEnabled = YES;
    [_coverView addTapCallBack:self sel:@selector(coverBgViewRemove:)];
    [[UIApplication sharedApplication].keyWindow addSubview:_coverView];

    _bgView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT , SCREEN_WIDTH, 240)];
    _bgView.backgroundColor = [UIColor whiteColor];
    [_coverView addSubview:_bgView];

    UIView *btnView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _bgView.width, 60)];
    btnView.backgroundColor = kColorDefultCell;
    [btnView setCornerDefault];
    [_bgView addSubview:btnView];

    UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(8, 8, 90, 40)];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBntClick:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn setCornerDefault];
    cancelBtn.backgroundColor= kColorDefultEdge;
    [btnView addSubview:cancelBtn];

    UIButton *sureBtn = [[UIButton alloc]initWithFrame:CGRectMake(_bgView.width-100, 8, 90, 40)];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sureBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [sureBtn setCornerDefault];
    sureBtn.backgroundColor = kColorDefult;
    [btnView addSubview:sureBtn];
    
    _pickerView = [[EFPickerView alloc] initWithFrame:CGRectMake(0, 60, _bgView.width, 180) dataArray:self.data rowHeight:35];
    [_bgView addSubview:_pickerView];

    if (@available(iOS 13.4, *)) {
        _datePicker.preferredDatePickerStyle = UIDatePickerStyleWheels;
    } else {
        // Fallback on earlier versions
    }

    [UIView animateWithDuration:0.3 animations:^{
        _bgView.top = SCREEN_HEIGHT-240;
    }];

}

- (void)coverBgViewRemove:(UITapGestureRecognizer *)view
{
    [UIView animateWithDuration:0.3 animations:^{
        _bgView.top = SCREEN_HEIGHT;
    }completion:^(BOOL finished) {
        [view.view removeFromSuperview];
    }];
}

- (void)cancelBntClick:(UIButton *)btn
{
    UIView *bgView = btn.superview.superview.superview ;
    [UIView animateWithDuration:0.3 animations:^{
        btn.superview.superview.top = SCREEN_HEIGHT;
    }completion:^(BOOL finished) {
        [bgView removeFromSuperview];
    }];
    
}

- (void)sureBtnClick:(UIButton *)btn
{
    if(ISEMPTY(self.pickerView.selecTitle)){
        self.dateLabel.text = [self getNowDateString];
    }else{
        self.dateLabel.text = self.pickerView.selecTitle;
    }
    
    UIView *bgView = btn.superview.superview.superview ;
    [UIView animateWithDuration:0.3 animations:^{
        btn.superview.superview.top = SCREEN_HEIGHT;
    }completion:^(BOOL finished) {
        [bgView removeFromSuperview];
    }];
    
    if(self.selectIndex == 0){
        [self.yejiModel getMyYejiDataWith:self.dateLabel.text];
    }else if(self.selectIndex == 1){
        [self.yejiModel getTeamDataWith:self.dateLabel.text];
    }else{
        [self.yejiModel getMyCommissionDataWith:self.dateLabel.text];
    }
}


- (void)setMyYejiWith:(NSDictionary *)dic{

    UILabel *tagLab = [[UILabel alloc] initWithFrame:CGRectMake(-12, 0, 100, 22)];
    tagLab.text = @"月明细";
    tagLab.textColor = kColorDefultCell;
    tagLab.font = [UIFont systemFontOfSize:13];
    tagLab.backgroundColor = UIColorFromRGB1(0xE5B580);
    [tagLab setCornerRedius:12];
    tagLab.textAlignment = NSTextAlignmentCenter;
    [_myYejiBgView addSubview:tagLab];
    
    UILabel *incomeLab = [[UILabel alloc] initWithFrame:CGRectMake(25, tagLab.bottom+10, 80, 24)];
    incomeLab.text = [NSString stringWithFormat:@"收入:%@",dic[@"inCome"]];
    incomeLab.textColor = kTitleColor_midden;
    incomeLab.font = [UIFont systemFontOfSize:13];
    [_myYejiBgView addSubview:incomeLab];
    
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, incomeLab.bottom+10, _myYejiBgView.width, _myYejiBgView.height-incomeLab.bottom-10)];
    [scrollView setContentSize:CGSizeMake(_myYejiBgView.width*5/4, 0)];
    [_myYejiBgView addSubview:scrollView];
    
    NSMutableArray *mutArray = [NSMutableArray array];
    [mutArray addObject:@{@"productName":@"产品名称",@"productFee":@"保费",@"commissionPercent":@"佣金率",@"commissionFee":@"佣金"}];
    if(![dic[@"commissionFeeList"] isEqual: @""] && dic[@"commissionFeeList"] != nil && [dic[@"commissionFeeList"] isKindOfClass:[NSArray class]]){
        [mutArray addObjectsFromArray:dic[@"commissionFeeList"]];
    }
    CGFloat width = _teamYejiBgView.width/4;
    CGFloat height = 30;
    for (int i = 0; i < mutArray.count; i++) {
        UIView *rowView = [[UIView alloc]initWithFrame:CGRectMake(0, i*height,_teamYejiBgView.width*5/4 , height)];
        if(i == 0) rowView.backgroundColor = UIColorFromRGB1(0xE5B580);
        [scrollView addSubview:rowView];
        
        NSDictionary *rowDic = mutArray[i];
        NSArray *rowArr = @[rowDic[@"productName"],rowDic[@"productFee"],rowDic[@"commissionPercent"],rowDic[@"commissionFee"]];
        for (int j = 0; j < rowArr.count; j++) {
            CGFloat left = 0;
            if(j == 0){
                width =_teamYejiBgView.width/2;
            }else{
                left = (j-1)*_teamYejiBgView.width/4 + _teamYejiBgView.width/2;
                width =_teamYejiBgView.width/4;
            }
            UILabel *cell = [[UILabel alloc]initWithFrame:CGRectMake(left, 0, width, height)];
            cell.textColor = kTitleColor_midden;
            cell.font = KFontSmall;
            cell.text = rowArr[j];
            cell.textAlignment = NSTextAlignmentCenter;
            if(i == 0){
                cell.textColor = kColorDefultCell;
            }else{
                [cell setViewEdgeWithBorderWidth:2 cornerRadius:0 borderColor:UIColorFromRGB1(0xFAF2E7)];
            }
            [rowView addSubview:cell];
        }
    }
    
}

- (void)setTeamYejiWith:(NSDictionary *)dic{
    
    NSMutableArray *mutArray = [NSMutableArray array];
    [mutArray addObject:@{@"jobNumber":@"工号",@"name":@"姓名号",@"policyFee":@"业绩业绩",@"policyQuantity":@"出单件"}];
    if(![dic[@"list"] isEqual: @""] && dic[@"list"] != nil && [dic[@"list"] isKindOfClass:[NSArray class]]){
        [mutArray addObjectsFromArray:dic[@"list"]];
    }
    CGFloat width = _teamYejiBgView.width/4;
    CGFloat height = 30;
    for (int i = 0; i < mutArray.count; i++) {
        UIView *rowView = [[UIView alloc]initWithFrame:CGRectMake(0, i*height, _teamYejiBgView.width, height)];
        if(i == 0) rowView.backgroundColor = UIColorFromRGB1(0xE5B580);
        [_teamYejiBgView addSubview:rowView];
        
        NSDictionary *rowDic = mutArray[i];
        NSArray *rowArr = @[rowDic[@"jobNumber"],rowDic[@"name"],rowDic[@"policyFee"],rowDic[@"policyQuantity"]];
        for (int j = 0; j < rowArr.count; j++) {
            UILabel *cell = [[UILabel alloc]initWithFrame:CGRectMake(j*width, 0, width, height)];
            cell.textColor = kTitleColor_midden;
            cell.font = KFontSmall;
            cell.text = rowArr[j];
            cell.textAlignment = NSTextAlignmentCenter;
            if(i == 0){
                cell.textColor = kColorDefultCell;
            }else{
                [cell setViewEdgeWithBorderWidth:2 cornerRadius:0 borderColor:UIColorFromRGB1(0xFAF2E7)];
            }
            [rowView addSubview:cell];
        }
    }
}

- (void)setMyCommissionDataWith:(NSDictionary *)dic{
    
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, _myCommsionBgView.width, _myCommsionBgView.height)];
    [scrollView setContentSize:CGSizeMake(_myYejiBgView.width*5/4, 0)];
    [_myCommsionBgView addSubview:scrollView];
    
    NSMutableArray *mutArray = [NSMutableArray array];
    [mutArray addObject:@{@"targetFee":@"年度标准业绩TC连续率",@"targetR13":@"R13连续率",@"targetR25":@"R25连续率",@"targetR37":@"R37连续率"}];
    if(dic != nil && ![dic isEqual: @""] && [dic isKindOfClass:[NSDictionary class]]){
        [mutArray addObject:@{@"targetFee":dic[@"targetFee"],@"targetR13":@"0",@"targetR25":@"0",@"targetR37":@"0"}];
    }
    CGFloat width = _teamYejiBgView.width/4;
    CGFloat height = 30;
    for (int i = 0; i < mutArray.count; i++) {
        UIView *rowView = [[UIView alloc]initWithFrame:CGRectMake(0, i*height,_teamYejiBgView.width*5/4 , height)];
        if(i == 0) rowView.backgroundColor = UIColorFromRGB1(0xE5B580);
        [scrollView addSubview:rowView];
        
        NSDictionary *rowDic = mutArray[i];
        NSArray *rowArr = @[rowDic[@"targetFee"],rowDic[@"targetR13"],rowDic[@"targetR25"],rowDic[@"targetR37"]];
        for (int j = 0; j < rowArr.count; j++) {
            CGFloat left = 0;
            if(j == 0){
                width =_teamYejiBgView.width/2;
            }else{
                left = (j-1)*_teamYejiBgView.width/4 + _teamYejiBgView.width/2;
                width =_teamYejiBgView.width/4;
            }
            UILabel *cell = [[UILabel alloc]initWithFrame:CGRectMake(left, 0, width, height)];
            cell.textColor = kTitleColor_midden;
            cell.font = KFontSmall;
            cell.text = rowArr[j];
            cell.textAlignment = NSTextAlignmentCenter;
            if(i == 0){
                cell.textColor = kColorDefultCell;
            }else{
                [cell setViewEdgeWithBorderWidth:2 cornerRadius:0 borderColor:UIColorFromRGB1(0xFAF2E7)];
            }
            [rowView addSubview:cell];
        }
    }
    
}

- (void)addViews{
    
    _myYejiBgView = [[UIView alloc]initWithFrame:CGRectMake(20, _dateView.bottom+10, SCREEN_WIDTH-40, 500)];
    [_myYejiBgView setHidden:NO];
    [self.scrollView addSubview:_myYejiBgView];
    
    _teamYejiBgView = [[UIView alloc]initWithFrame:CGRectMake(20, _dateView.bottom+10, SCREEN_WIDTH-40, 500)];
    [_teamYejiBgView setHidden:YES];
    [self.scrollView addSubview:_teamYejiBgView];
    
    _myCommsionBgView = [[UIView alloc]initWithFrame:CGRectMake(20, _dateView.bottom+10, SCREEN_WIDTH-40, 500)];
    [_myCommsionBgView setHidden:YES];
    [self.scrollView addSubview:_myCommsionBgView];
}

- (UIScrollView *)scrollView{
    
    if (nil == _scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, KNavFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT_EXCEPTNAV)];
        _scrollView.delegate = self ;
        _scrollView.backgroundColor = [UIColor whiteColor];
        _scrollView.contentSize = CGSizeMake(0, SCREEN_HEIGHT+120);
        _scrollView.alwaysBounceVertical = YES ;
    }
    return _scrollView;
}

- (UIView *)topView{
    if(nil == _topView){
        _topView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 115)];
        EFAppContext *appc = [EFAppContext sharedContext];

        UIImageView *headerIconImg = [[UIImageView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-80)/2, 0, 80, 80)];
        headerIconImg.layer.borderWidth = 2;
        headerIconImg.layer.borderColor = kColorDefultEdge.CGColor;
        [headerIconImg setCornerDefaultHalf];
        [headerIconImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",appc.headUrl]] placeholderImage:kDefaultImage];
        [_topView addSubview:headerIconImg];

        UILabel *nickNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, headerIconImg.bottom+5, SCREEN_WIDTH, 25)];
        nickNameLabel.text = appc.userName;
        nickNameLabel.font = kFontMidden;
        nickNameLabel.textColor = kTitleColor_black;
        nickNameLabel.textAlignment = NSTextAlignmentCenter;
        [_topView addSubview:nickNameLabel];
    }
    return _topView;
}

- (void)yejiBtnClick:(YejiTypeBtn *)btn{
    
    btn.titLabel.font = [UIFont systemFontOfSize:16];
    btn.titLabel.textColor = UIColorFromRGB1(0xE5B580);
    for (YejiTypeBtn *typeBtn in self.typeSelectView.subviews) {
        if(typeBtn.tag != btn.tag){
            typeBtn.titLabel.font = [UIFont systemFontOfSize:14];
            typeBtn.titLabel.textColor = kTitleColor_midden;
        }
    }
    
    switch (btn.tag-100){
        case 0:
            self.selectIndex = 0;
            [_myYejiBgView setHidden:NO];
            [_teamYejiBgView setHidden:YES];
            [_myCommsionBgView setHidden:YES];
            [self.yejiModel getMyYejiDataWith:self.dateLabel.text];
            break;
        case 1:
            self.selectIndex = 1;
            [_myYejiBgView setHidden:YES];
            [_teamYejiBgView setHidden:NO];
            [_myCommsionBgView setHidden:YES];
            [self.yejiModel getTeamDataWith:self.dateLabel.text];
            break;
        case 2:
            self.selectIndex = 2;
            [_myYejiBgView setHidden:YES];
            [_teamYejiBgView setHidden:YES];
            [_myCommsionBgView setHidden:NO];
            [self.yejiModel getMyCommissionDataWith:self.dateLabel.text];
            break;
        default:
            break;
    }

}

- (UIView *)dateView{
    if(nil == _dateView){
        _dateView = [[UIView alloc]initWithFrame:CGRectMake(0, _typeSelectView.bottom, self.scrollView.width, 45)];
        [_dateView addTapCallBack:self sel:@selector(dateBgViewTap)];

        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(12, 0,_dateView.width-24, 1)];
        line.backgroundColor = UIColorFromRGB1(0xE5B580);
        [_dateView addSubview:line];
        
        UIImageView *leftImg = [[UIImageView alloc]initWithFrame:CGRectMake(20, line.bottom+16, 20, 19)];
        leftImg.image = kImage(@"calendar");
        [_dateView addSubview:leftImg];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(leftImg.right+5, leftImg.top, 60, leftImg.height)];
        _dateLabel = titleLabel;
//        titleLabel.text = @"日期选择";
        titleLabel.text = [self getNowDateString];
        titleLabel.font = [UIFont systemFontOfSize:14];
        titleLabel.textColor = kTitleColor_midden;
        
        [_dateView addSubview:titleLabel];
        
        UIImageView *rightImg = [[UIImageView alloc]initWithFrame:CGRectMake(titleLabel.right, titleLabel.top+2, 16, 16)];
        rightImg.image = kImage(@"down");
        [_dateView addSubview:rightImg];
    }
    return _dateView;
}

- (UIView *)typeSelectView{
    if(nil == _typeSelectView){
        _typeSelectView = [[UIView alloc]initWithFrame:CGRectMake(0, _topView.bottom+10, self.scrollView.width, 45)];
        
        NSArray *titleArray = @[@"我的业绩",@"团队业绩",@"我的考核"];
        CGFloat width = self.scrollView.width/3;
        for (int i = 0 ; i < 3; i++) {
            YejiTypeBtn *btn = [[YejiTypeBtn alloc] initWithFrame:CGRectMake(i*width, 0, width, 45)];
            btn.tag = 100+i;
            btn.titLabel.text = titleArray[i];
            btn.titLabel.font = [UIFont systemFontOfSize:14];
            btn.titLabel.textColor = kTitleColor_midden;
            [btn addTarget:self action:@selector(yejiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [_typeSelectView addSubview:btn];
            
            if(i == 0){
                btn.titLabel.font = [UIFont systemFontOfSize:16];
                btn.titLabel.textColor = UIColorFromRGB1(0xE5B580);
            }
        }
    }
    return _typeSelectView;
}

- (YejiModel *)yejiModel{

    if (nil == _yejiModel) {
        _yejiModel = [[YejiModel alloc]initWithDelegate:self cache:NO];
    }
    return _yejiModel;
}

//数据获取
- (NSMutableArray<NSString *> *)data{
    if (!_data) {
        _data = [[NSMutableArray alloc] init];
        //当前日期时间
        NSDate *currentDate = [NSDate date];
        //设定数据格式为xxxx-mm
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM"];
        //通过日历可以直接获取前几个月的日期，所以这里直接用该类的方法进行循环获取数据
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
        NSString *dateStr = [formatter stringFromDate:currentDate];
        NSInteger lastIndex = 0;
        NSDate *newdate;
        //循环获取可选月份，从当前月份到最小月份，直接用字符串的比较来判断是否大于设定的最小日期
        while (!([dateStr compare:self.minDateStr] == NSOrderedAscending)) {
            [_data addObject:dateStr];
            lastIndex--;
            //获取之前n个月, setMonth的参数为正则向后，为负则表示之前
            [lastMonthComps setMonth:lastIndex];
            newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
            dateStr = [formatter stringFromDate:newdate];
        }
    }
    return _data;
}

- (NSString *)getNowDateString{
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    return [formatter stringFromDate:currentDate];
}

@end
